<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <CorporateSectorCascader ref="cascaderRef" :configCascader="configCascader2"
              @changeCascader="changeCascader2" />

            <a-form-item label="仓库" label-col-flex="65px">
              <a-select popup-container="html" class="bacClass" :style="{ width: '228px' }"
                v-model="pageData.warehouseName" :disabled="pageData.companyName == ''" allow-clear>
                <a-option v-for="item in pageData.inShelveList2" :key="item.id" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <!-- <a-form-item label="织布单号">
              <a-input :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="pageData.clothfiyCode"
                @press-enter="huiche" />
            </a-form-item> -->
            <a-form-item label="退库单号" v-if="permissionStore.hasPermisson('pbtkgl.cx')">
              <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch" class="bacClass"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.dropDownData" @press-enter="huiche" />
            </a-form-item>
            <a-form-item label="日期" v-if="permissionStore.hasPermisson('pbtkgl.cx')">
              <a-date-picker popup-container="html" v-model="pageData.beginDate" placeholder="" class="bacClass" />至
              <a-date-picker popup-container="html" v-model="pageData.endDate" class="bacClass" placeholder="" />
            </a-form-item>
            <a-form-item label="单据状态" v-if="permissionStore.hasPermisson('pbtkgl.cx')">
              <a-select popup-container="html" :style="{ width: '200px' }" class="bacClass"
                v-model="pageData.returnState" :filter-option="false" allow-clear>
                <a-option :value="1">已退库未接收</a-option>
                <a-option :value="2">已退库已接收</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="条码号" v-if="permissionStore.hasPermisson('pbtkgl.cx')">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.clothfiyCode" @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar class="gesture" :items="pageData.btnList" @select="selectHandler" @export="exports">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>

    </template>

    <template #pageTabel>
      <!--
                        表格插件
                    -->
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady"
          @columnResized="onColumnResized" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible"
          style="height: calc(100% - 45px);" :defaultColDef="defaultColDef" class="ag-theme-alpine"
          :rowData="table.dataList" :localeText="localeText1" :columnDefs="tc"></AgGridVuesCopys>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
          @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="size"
          :current="page" />
      </a-spin>
    </template>

  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { pagingList } from '@/api/paging'
// 引入

import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface BrandInfo {
  id: any
  // brandCode: string
  brandName: string
  clothClass: string
  remark: string
  deleteState: number | string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

export default {
  name: 'ReturningWarehouseList',

  setup() {
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    const configCascader2 = ref<{}>({
      corporateWidth: '228px', //公司宽度
      size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
      corporateName: '公司', //公司label
      cascaderShow: 'sector', //配置部门不显示
    })
    const changeCascader2 = (data: any) => {
      pageData.warehouseName = ''
      const { corporateId, corporateLabel } = data
      pageData.companyName = corporateLabel
      pageData.companyId = corporateId
      focusShelve2()
    }
    const focusShelve2 = async () => {
      try {
        pageData.loading = true
        let { code, data, message } = await post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: { firmId: pageData.companyId, warehouseTypeName: '坯布仓,次布仓', virtuallyState: 0 },
        })
        if (code == 200) {
          pageData.inShelveList2 = data
          pageData.loading = false
          return
        }
      } finally {
        pageData.loading = false
      }
    }
    const cascaderRef = ref()
    function doRefresh() {
      pageData.pageLoading = true
      updateGridState01()

      post({
        url: 'wms/GreyStockReturn/getAllPage',
        data: {
          page: page.value,
          size: size.value,
          beginDate: pageData.beginDate,
          endDate: pageData.endDate,
          returnState: pageData.returnState,
          stockReturnCode: pageData.dropDownData,
          clothfiyCode: pageData.clothfiyCode,
          companyId: pageData.companyId,
          warehouseId: pageData.warehouseName
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)

            // 查询方法改

            gridOption.value.setRowData(data.list)

            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'companyName',
        dataIndex: 'companyName',
        width: 150,
      },
      {
        title: '仓库名称',
        key: 'warehouseName',
        dataIndex: 'warehouseName',
        width: 150,
      },
      {
        title: '退库单号',
        key: 'stockReturnCode',
        dataIndex: 'stockReturnCode',
        width: 150,
      },

      {
        title: '织布单号',
        key: 'planOrderCode',
        dataIndex: 'planOrderCode',
        width: 150,
      },
      {
        title: '条码号',
        key: 'clothfiyCode',
        dataIndex: 'clothfiyCode',
        width: 150,
      },
      {
        title: '客户',
        key: 'customName',
        dataIndex: 'customName',
        width: 150,
      },
      {
        title: '坯布编号',
        key: 'greyCode',
        dataIndex: 'greyCode',
        width: 150,
      },
      {
        title: '坯布名称',
        key: 'greyName',
        dataIndex: 'greyName',
        width: 150,
      },
      {
        title: '坯布批号',
        key: 'greyBatchNo',
        dataIndex: 'greyBatchNo',
        width: 150,
      },
      {
        title: '机台号',
        key: 'machineCode',
        dataIndex: 'machineCode',
        width: 150,
      },
      {
        title: '匹号',
        key: 'horseNo',
        dataIndex: 'horseNo',
        width: 150,
      },
      {
        title: '退库原因',
        key: 'returnReason',
        dataIndex: 'returnReason',
        width: 150,
      },
      {
        title: '退库人员',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '退库日期',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 150,
      },
      {
        title: '接收人员',
        key: 'receiveName',
        dataIndex: 'receiveName',
        width: 150,
      },
      {
        title: '接收日期',
        key: 'receiveTime',
        dataIndex: 'receiveTime',
        width: 150,
      },
      {
        title: '单据状态',
        key: 'returnState',
        slotName: 'returnState',
        width: 150,
        fixed: 'right',
      },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      obj['width'] = '250px'
      if (o.slotName === 'returnState') {
        obj['resizable'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 150
        obj['cellRenderer'] = {
          template: `<a-space> <el-tag type="warning" v-if="params.data.returnState==1">已退库未接收</el-tag>
          <el-tag type="success" v-else>已退库已接收</el-tag></a-space>`,
          setup(props: any) {

            return {

            }
          },
        }
        obj['filterParams'] = {
          valueFormatter: function (params: any) {
            return params.value == '1'
              ? '已退库未接收'
              : '已退库已接收'
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      returnState: any
      endDate: any
      beginDate: any,
      clothfiyCode: any,
      companyName: any,
      companyId: any,
      inShelveList2: any
    }>({
      inShelveList2: [],
      companyName: '',
      companyId: '',
      nameList: [],
      showAdd: false,
      sideTitle: '',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      returnState: null,
      endDate: "",
      beginDate: "",
      clothfiyCode: '',
      // configCascader2:'',
      // changeCascader2:'',
    })



    onMounted(() => {
      doRefresh()
      // 切换tap到本页面执行的方法
      // emitter.on('BrandInfo', () => {
      //   // selCxAll1({});
      //   doRefresh()
      // })
    })
    //查询
    const selectHandler = () => {
      page.value = 1
      doRefresh()
    }

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }


    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      else {
        // let idList: any = []
        // gridOption.value.getSelectedRows().forEach(function (o: any) {
        //   idList.push(o['id'])
        // })
        //将表头拼接出来
        let head =
          '<th>退库单号</th><th>织布单号</th><th>客户</th><th>坯布编号</th><th>坯布名称</th><th>坯布批号</th><th>机台号</th><th>匹号</th><th>退库原因</th><th>退库人员</th><th>退库日期</th><th>接收人员</th><th>接收日期</th><th>单据状态</th>'
        //拿到当前表格数据与勾选的行做筛选

        // let nowRow = table.dataList.filter(function (o) {
        //   return (
        //     gridOption.value
        //       .getSelectedRows()
        //       .map((o: any) => {
        //         return o.id
        //       })
        //       .indexOf(o['id']) !== -1
        //   )
        // })
        let body = ''
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          body += '<tr><td>' + o['stockReturnCode'] + '</td>'
          body += '<td>' + o['planOrderCode'] + '</td>'
          body += '<td>' + o['customName'] + '</td>'
          body += '<td>' + o['greyCode'] + '</td>'
          body += '<td>' + o['greyName'] + '</td>'
          body += '<td>' + o['greyBatchNo'] + '</td>'
          body += '<td>' + o['machineCode'] + '</td>'
          body += '<td>' + o['horseNo'] + '</td>'
          body += '<td>' + o['returnReason'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['receiveName'] + '</td>'
          body += '<td>' + o['receiveTime'] + '</td>'
          body += '<td>' + (o['returnState'] == 1 ? '已退库未接收' : '已退库已接收') + '</td>'

          body += '</tr>'
        })
        tableToXlsx(head, '坯布退库列表', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }


    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('pbtkgl.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('pbtkgl.dc')) {
      pageData.btnList.push('导出')
    }



    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const huiche = () => {
      page.value = 1
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    const localeText1: any = ref(localeText)
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('ReturningWarehouseList-1', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    const onColumnVisible = () => {
      saveGridState01()
    }
    return {
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      selectHandler,
      exports,
      headerShow,
      handleChange,
      gridReady,
      permissionStore,
      focusShelve2,
      cascaderRef,
      configCascader2,
      changeCascader2
    }
  },
  components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
}
</script>

<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>